package com.ufo.store.management.ui.activity;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nineoldandroids.view.ViewHelper;
import com.ufo.store.management.BarApplication;
import com.ufo.store.management.R;
import com.ufo.store.management.adapter.Isszmbalv3StockRecyclerViewAdapter;

import com.ufo.store.management.adapter.SearchHistoryRecyclerViewAdapter;
import com.ufo.store.management.database.DatabaseManager;
import com.ufo.store.management.entity.Isszmbalv3StockInfo;
import com.ufo.store.management.entity.Isszmbalv3SupcustInfo;
import com.ufo.store.management.entity.SerializableList;
import com.ufo.store.management.entity.SerializableMap;
import com.ufo.store.management.common.Config;
import com.ufo.store.management.utils.DialogUtil;
import com.ufo.store.management.utils.ScreenUtil;
import com.ufo.store.management.utils.StatusBarUtil;
import com.ufo.store.management.utils.Utils;
import com.ufo.store.management.widget.dialog.CHistoryDeleteDialog;
import com.ufo.store.management.widget.layout.TouchFrameLayout;
import com.ufo.store.management.widget.recyclerview.EndlessRecyclerOnScrollListener;
import com.ufo.store.management.widget.zxing.MipcaActivityCapture;
import com.github.ybq.android.spinkit.SpinKitView;

import java.util.List;
import java.util.concurrent.Semaphore;

import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Created by taoli on 2016/12/22 0022.
 */

public class SearchIsszmbalv3StockActivity extends BaseActivity implements Handler.Callback {
    private String TAG = SearchIsszmbalv3StockActivity.class.getSimpleName();
    private final int ACTIVITY_RESULT_STOCK_DETAIL = 100;
    private final int ACTIVITY_RESULT_SPEECH = 101;
    private final int ACTIVITY_RESULT_BARCODE_PICK = 102;

    public final static int SEARCH_BY_STOCKNO = 1;
    public final static int SEARCH_BY_STOCKNAME = 2;
    public final static int SEARCH_BY_STOCKSPELL = 3;

    private static final int LOAD_DATA_FINISH = 10;
    private static final int REFRESH_DATA_FINISH = 11;

    private ImageView mReturnIv = null;
    private Handler mHandler = null;
    private ConstraintLayout mSearchControlCl = null;
    private EditText mSearchEt = null;

    private ConstraintLayout condition_cl = null;
    private ConstraintLayout mSearchResultcl = null;
    private RelativeLayout mHistoryRl = null;
    private SpinKitView spin_kit = null;
    private LinearLayout mGetStockFailTipLy = null;
    private TextView mStockFailTipTv = null;
    private ImageView mStyleIv = null;

    private TextView stockname_tv;
    private TextView stockid_tv;
    private TextView stockcost_tv;

    private ImageView stockname_iv;
    private ImageView stockid_iv;
    private ImageView stockcost_iv;

    //private MaterialSpinner spinner = null;
    private PopupWindow mModeSelectPopWindow = null;
    private TextView search_mode_tv = null;
    private ImageView search_mode_iv = null;

    private RecyclerView mIsszmbalv3StockRecyclerView = null;
    private Isszmbalv3StockRecyclerViewAdapter mIsszmbalv3StockRecyclerViewAdapter = null;
    private PtrClassicFrameLayout mPtrFrame;

    private View mActivityRootView = null;
    private TouchFrameLayout mSearchMaskV = null;
    private ImageView mDeleteIv = null;
    private ImageView mSpeechIv = null;

    private ImageView mHistoryDeleteIv = null;
    private RecyclerView mSearchHistoryRecyclerView = null;
    private GridLayoutManager mTypeGridLayoutManager = null;
    private SearchHistoryRecyclerViewAdapter mSearchHistoryRecyclerViewAdapter = null;
    private CHistoryDeleteDialog mCHistoryDeleteDialog = null;

    private String mSearchStr = null;

    private int mReadIndex = 0;
    private boolean mIsSearchControlRlHided = false;
    private int mSearchMode = -1;
    private String mStockTypeId = "-1";

    final Semaphore semp = new Semaphore(1);
    private Object mLock = new Object();

    private SerializableMap mIsszmbalv3StockTypeMap = new SerializableMap();
    private SerializableList mIsszmbalv3SupcustInfoSerializableList;

    private int mMoveStartY = 0;
    private int mMoveDurY = 0;

    private int ListStyle;

    private boolean mCanLoadMore = true;

    private int SortMode = -1;     // 0:名字升序   1：名字降序    2：ID升序  3：ID降序    4：价格升序     5：价格降序

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
        initView();
        StatusBarUtil.StatusBarLightMode(this, R.color.app_bar_color, true);
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case REFRESH_DATA_FINISH:
                if (mIsszmbalv3StockRecyclerViewAdapter != null) {
                    final List<Isszmbalv3StockInfo> data = (List<Isszmbalv3StockInfo>) msg.obj;
                    mIsszmbalv3StockRecyclerViewAdapter.setData(data);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyDataSetChanged();
                    getSearchHistory();
                    showResultView();
                }
                semp.release();
                break;
            case LOAD_DATA_FINISH:
                if (mIsszmbalv3StockRecyclerViewAdapter != null) {
                    final List<Isszmbalv3StockInfo> data = (List<Isszmbalv3StockInfo>) msg.obj;
                    mIsszmbalv3StockRecyclerViewAdapter.insertData(data);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyDataSetChanged();
                    showResultView();
                }
                semp.release();
                break;
        }
        return false;
    }

    private void initData() {
        mHandler = new Handler(this);
        Intent intent = getIntent();
        if (intent != null) {
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                mIsszmbalv3StockTypeMap = (SerializableMap) bundle.getSerializable("Isszmbalv3StockType");
                mIsszmbalv3SupcustInfoSerializableList = (SerializableList) bundle.getSerializable("Isszmbalv3SupcustInfo");
                if (bundle.containsKey("SearchMode")) {
                    mSearchMode = bundle.getInt("SearchMode");
                }
                if (bundle.containsKey("StockTypeId")) {
                    mStockTypeId = bundle.getString("StockTypeId");
                }
            }
        }

        ListStyle = Config.getIsszmbalv3StockListStyle();
    }

    private void initView() {
        setContentView(R.layout.activity_isszmbalv3_stock_search);
        mReturnIv = (ImageView) findViewById(R.id.iv_back);
        mReturnIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InputMethodManager inputManager = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0); //强制隐藏键盘
                finishAfterTransition();
            }
        });

        mPtrFrame = (PtrClassicFrameLayout) findViewById(R.id.ptr);
        mPtrFrame.setLastUpdateTimeRelateObject(this);
        mPtrFrame.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header) && !mIsSearchControlRlHided;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getIsszmbalv3StockResultInfoList(true);
            }
        });

        mStyleIv = (ImageView) findViewById(R.id.style_iv);
        mStyleIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ListStyle == 1) {
                    ListStyle = 2;
                    mStyleIv.setImageResource(R.drawable.ic_grid_style_selector);
                    mIsszmbalv3StockRecyclerViewAdapter.setStyle(ListStyle);
                    mIsszmbalv3StockRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
                } else if (ListStyle == 2) {
                    ListStyle = 1;
                    mStyleIv.setImageResource(R.drawable.ic_list_style_selector);
                    mIsszmbalv3StockRecyclerViewAdapter.setStyle(ListStyle);
                    mIsszmbalv3StockRecyclerView.setLayoutManager(new LinearLayoutManager(SearchIsszmbalv3StockActivity.this));
                }

                Config.setIsszmbalv3StockListStyle(ListStyle);
            }
        });
        if (ListStyle == 2) {
            mStyleIv.setImageResource(R.drawable.ic_grid_style_selector);
        } else if (ListStyle == 1) {
            mStyleIv.setImageResource(R.drawable.ic_list_style_selector);
        }
        mActivityRootView = findViewById(R.id.activityRoot);
        mActivityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                mActivityRootView.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = mActivityRootView.getRootView().getHeight() - rect.bottom;
                if (rootInvisibleHeight > ScreenUtil.getScreenSize(getActivity())[1] / 3) {
                    displayWithAnimator(mSearchMaskV, 1.0f, 500);
                } else {
                    displayWithAnimator(mSearchMaskV, .0f, 500);
                }
            }
        });

//        spinner = (MaterialSpinner) findViewById(R.id.spinner);
//        spinner.setItems("序号/条码", "名称", "缩写");
//        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
//            @Override
//            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
//                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(mIsszmbalv3StockRecyclerView.getWindowToken(), 0);
//                switch (position) {
//                    case 0:
//                        mSearchMode = SEARCH_BY_STOCKNO;
//                        Intent intent = new Intent();
//                        intent.setClass(SearchIsszmbalv3StockActivity.this, MipcaActivityCapture.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                        startActivityForResult(intent, ACTIVITY_RESULT_BARCODE_PICK);
//                        break;
//                    case 1:
//                        mSearchMode = SEARCH_BY_STOCKNAME;
//                        getIsszmbalv3StockResultInfoList(true);
//                        break;
//                    case 2:
//                        mSearchMode = SEARCH_BY_STOCKSPELL;
//                        getIsszmbalv3StockResultInfoList(true);
//                        break;
//                }
//            }
//        });

        condition_cl = (ConstraintLayout) findViewById(R.id.condition_cl);
        mSearchControlCl = (ConstraintLayout) findViewById(R.id.search_control_cl);
        mHistoryRl = (RelativeLayout) findViewById(R.id.history_rl);
        mHistoryDeleteIv = (ImageView) findViewById(R.id.history_delete_iv);
        mHistoryDeleteIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDeleteHistoryDialog();
            }
        });

        stockname_tv = (TextView) findViewById(R.id.stockname_tv);
        stockid_tv = (TextView) findViewById(R.id.stockid_tv);
        stockcost_tv = (TextView) findViewById(R.id.stockcost_tv);

        stockname_iv = (ImageView) findViewById(R.id.stockname_iv);
        stockid_iv = (ImageView) findViewById(R.id.stockid_iv);
        stockcost_iv = (ImageView) findViewById(R.id.stockcost_iv);

        stockname_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                stockid_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockcost_tv.setTextColor(Color.parseColor("#5c5c5c"));
                stockname_iv.setImageResource(R.drawable.ic_triangle_press);
                stockid_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_dark);
                if( SortMode != 0 ) {
                    SortMode = 0;
                    stockname_iv.animate().rotation(180);
                }else{
                    SortMode = 1;
                    stockname_iv.animate().rotation(0);
                }
                stockid_iv.animate().rotation(0);
                stockcost_iv.animate().rotation(0);
                getIsszmbalv3StockResultInfoList(true);
            }
        });
        stockid_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockid_tv.setTextColor(getResources().getColor(R.color.app_key_color));
//                stockcost_tv.setTextColor(Color.parseColor("#5c5c5c"));
                stockname_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockid_iv.setImageResource(R.drawable.ic_triangle_press);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockname_iv.animate().rotation(0);
                if( SortMode != 2 ) {
                    SortMode = 2;
                    stockid_iv.animate().rotation(180);
                }else {
                    SortMode = 3;
                    stockid_iv.animate().rotation(0);
                }
                stockcost_iv.animate().rotation(0);
                getIsszmbalv3StockResultInfoList(true);
            }
        });
        stockcost_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                stockname_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockid_tv.setTextColor(Color.parseColor("#5c5c5c"));
//                stockcost_tv.setTextColor(getResources().getColor(R.color.app_key_color));
                stockname_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockid_iv.setImageResource(R.drawable.ic_triangle_dark);
                stockcost_iv.setImageResource(R.drawable.ic_triangle_press);
                stockname_iv.animate().rotation(0);
                stockid_iv.animate().rotation(0);
                if( SortMode != 4 ) {
                    SortMode = 4;
                    stockcost_iv.animate().rotation(180);
                }else {
                    SortMode = 5;
                    stockcost_iv.animate().rotation(0);
                }
                getIsszmbalv3StockResultInfoList(true);
            }
        });

        mSearchHistoryRecyclerView = (RecyclerView) findViewById(R.id.searchhistory_recyclerview);
        mSearchHistoryRecyclerViewAdapter = new SearchHistoryRecyclerViewAdapter(SearchIsszmbalv3StockActivity.this);
        mSearchHistoryRecyclerViewAdapter.setOnClickListener(new SearchHistoryRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onItemClick(View v, int position) {
                mSearchStr = mSearchHistoryRecyclerViewAdapter.getItem(position);
                mSearchEt.setText(mSearchStr);
                getIsszmbalv3StockResultInfoList(true);
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
            }

            @Override
            public void onItemLongClick(View v, int position) {

            }
        });
        mTypeGridLayoutManager = new GridLayoutManager(SearchIsszmbalv3StockActivity.this,80);
        mTypeGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                String itemStr = mSearchHistoryRecyclerViewAdapter.getItem(position);
                String subStr = itemStr.substring(0, 0 + 1);
                int s = 6;
                if (subStr.getBytes().length >= 2) {
                    s = s + itemStr.getBytes().length * 2;
                }else{
                    s = s + itemStr.getBytes().length * 3;
                }
                return Math.max(Math.min(s, 31), 11);
            }
        });
        mSearchHistoryRecyclerView.setNestedScrollingEnabled(false);
        mSearchHistoryRecyclerView.setLayoutManager(mTypeGridLayoutManager);
        mSearchHistoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mSearchHistoryRecyclerView.setHasFixedSize(true);
        mSearchHistoryRecyclerView.setAdapter(mSearchHistoryRecyclerViewAdapter);

        mSearchMaskV = (TouchFrameLayout) findViewById(R.id.v_search_mask);
        mSearchMaskV.setClickListener(new TouchFrameLayout.OnClick() {
            public void onClick(View v) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mIsszmbalv3StockRecyclerView.getWindowToken(), 0);
                displayWithAnimator(mSearchMaskV, .0f, 500);
            }
        });

        search_mode_iv = (ImageView) findViewById(R.id.search_mode_iv);
        search_mode_tv = (TextView) findViewById(R.id.search_mode_tv);
        search_mode_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mModeSelectPopWindow.isShowing()) {
                    mModeSelectPopWindow.showAsDropDown(v);
                    search_mode_iv.animate().rotation(180);
                } else {
                    mModeSelectPopWindow.dismiss();
                }
            }
        });

        mSearchEt = (EditText) findViewById(R.id.search_et);
        mSearchEt.addTextChangedListener(new android.text.TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSearchStr = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    mDeleteIv.setVisibility(View.GONE);
                    mSpeechIv.setVisibility(View.VISIBLE);
                } else {
                    mDeleteIv.setVisibility(View.VISIBLE);
                    mSpeechIv.setVisibility(View.GONE);
                }
                mHistoryRl.setVisibility(View.VISIBLE);
                mPtrFrame.setVisibility(View.GONE);
                mGetStockFailTipLy.setVisibility(View.GONE);
            }
        });
        mSearchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                    }
                    mIsszmbalv3StockRecyclerView.requestFocus();
                    if( !TextUtils.isEmpty(mSearchEt.getText().toString())) {
                        DatabaseManager.insertInputHistory(SearchIsszmbalv3StockActivity.this, mSearchEt.getText().toString());
                    }
                    mSearchStr = mSearchEt.getText().toString();
                    getIsszmbalv3StockResultInfoList(true);
                    return true;
                }
                return false;
            }
        });

        mDeleteIv = ((ImageView) findViewById(R.id.iv_search_delete));
        mDeleteIv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mSearchEt.setText("");
                mSearchEt.requestFocus();
                InputMethodManager inputManager = (InputMethodManager) mSearchEt.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mSearchEt, 0);
            }
        });

        mSpeechIv = ((ImageView) findViewById(R.id.iv_search_speech));
        mSpeechIv.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                startActivityForResult(new Intent(SearchIsszmbalv3StockActivity.this, VoiceActivity.class), ACTIVITY_RESULT_SPEECH);
            }
        });

        mSearchResultcl = (ConstraintLayout) findViewById(R.id.search_result_cl);
        spin_kit = (SpinKitView) findViewById(R.id.spin_kit);
        mGetStockFailTipLy = (LinearLayout) findViewById(R.id.get_stock_fail_tip_ly);
        mStockFailTipTv = (TextView) findViewById(R.id.get_stock_list_fail_tv);

        mIsszmbalv3StockRecyclerView = (RecyclerView) findViewById(R.id.stock_recyclerview);
        if (ListStyle == 1) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new LinearLayoutManager(SearchIsszmbalv3StockActivity.this));
        } else if (ListStyle == 2) {
            mIsszmbalv3StockRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
        }
        mIsszmbalv3StockRecyclerViewAdapter = new Isszmbalv3StockRecyclerViewAdapter(SearchIsszmbalv3StockActivity.this, ListStyle, mIsszmbalv3StockTypeMap.getMap());
        mIsszmbalv3StockRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mIsszmbalv3StockRecyclerView.setHasFixedSize(true);
        mIsszmbalv3StockRecyclerView.setAdapter(mIsszmbalv3StockRecyclerViewAdapter);
        mIsszmbalv3StockRecyclerViewAdapter.setOnClickListener(new Isszmbalv3StockRecyclerViewAdapter.OnClickListener() {
            @Override
            public void onDetailClick(int position) {
                Isszmbalv3StockInfo isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(SearchIsszmbalv3StockActivity.this, Isszmbalv3StockSalesActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("StockNo", isszmbalv3StockInfo.item_no);
                bundle.putString("StockName", isszmbalv3StockInfo.item_name);
                toIntent.putExtras(bundle);
                startActivity(toIntent);
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onDeleteClick(int position) {
                showDeleteItemDialog(position);
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }

            @Override
            public void onItemClick(View v, int position) {
                Isszmbalv3StockInfo Isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(position);
                Intent toIntent = new Intent(SearchIsszmbalv3StockActivity.this, Isszmbalv3StockEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("Isszmbalv3StockInfo", Isszmbalv3StockInfo);
                bundle.putSerializable("Isszmbalv3StockType", mIsszmbalv3StockTypeMap);
                bundle.putSerializable("Isszmbalv3SupcustInfo", mIsszmbalv3SupcustInfoSerializableList);
                toIntent.putExtras(bundle);

//                // Now we can start the Activity, providing the activity options as a bundle
//                if( ListStyle == 2) {
//                    /**
//                     * Now create an {@link android.app.ActivityOptions} instance using the
//                     * {@link ActivityOptionsCompat#makeSceneTransitionAnimation(Activity, Pair[])} factory
//                     * method.
//                     */
//                    @SuppressWarnings("unchecked")
//                    ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(
//                            SearchIsszmbalv3StockActivity.this,
//                            // Now we provide a list of Pair items which contain the view we can transitioning
//                            // from, and the name of the view it is transitioning to, in the launched activity
//                            v.findViewById(R.id.icon_rl), Isszmbalv3StockEditActivity.VIEW_NAME_HEADER_IMAGE);
//                    startActivityForResult(toIntent, ACTIVITY_RESULT_STOCK_DETAIL, activityOptions.toBundle());
//                }
//                else
                    startActivityForResult(toIntent,ACTIVITY_RESULT_STOCK_DETAIL);
            }

            @Override
            public void onItemLongClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMenuClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                } else {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(position);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(position, "menu");
                }
            }

            @Override
            public void onMaskClick(View v, int position) {
                int i = mIsszmbalv3StockRecyclerViewAdapter.getLongPressedIndex();
                if (i != -1) {
                    mIsszmbalv3StockRecyclerViewAdapter.setLongPressedIndex(-1);
                    mIsszmbalv3StockRecyclerViewAdapter.notifyItemChanged(i, "menu");
                }
            }
        });

        mIsszmbalv3StockRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mMoveDurY = 0;
                        mMoveStartY = 0;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        if (mMoveStartY == 0) {
                            mMoveStartY = (int) event.getY();
                        }
                        int _TempY = (int) event.getY();
                        mMoveDurY = _TempY - mMoveStartY;   //负数向上移动，正数向下移动
                        if (mMoveDurY < -Utils.dp2px(getResources(), 80) && mIsSearchControlRlHided == false) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsSearchControlRlHided = true;
                            menuCollapse();
                        } else if (mMoveDurY > Utils.dp2px(getResources(), 80) && mIsSearchControlRlHided == true) {
                            mMoveDurY = 0;
                            mMoveStartY = 0;
                            mIsSearchControlRlHided = false;
                            menuExpand();
                        }
                        break;
                }
                return false;
            }
        });

        mIsszmbalv3StockRecyclerView.addOnScrollListener(mOnScrollListener);

        //看传入的参数是否直接开始检索
        if (mSearchMode != -1) {
            if (mSearchMode == SEARCH_BY_STOCKNO) {
                search_mode_tv.setText("条码/序号");
                //spinner.setSelectedIndex(0);
                Intent intent = new Intent();
                intent.setClass(SearchIsszmbalv3StockActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, ACTIVITY_RESULT_BARCODE_PICK);
            } else if (mSearchMode == SEARCH_BY_STOCKNAME) {
                search_mode_tv.setText("中文名称");
                //spinner.setSelectedIndex(1);
            } else if (mSearchMode == SEARCH_BY_STOCKSPELL) {
                search_mode_tv.setText("拼音缩写");
                //spinner.setSelectedIndex(2);
            }
        } else {
            mSearchMode = SEARCH_BY_STOCKSPELL;
            search_mode_tv.setText("拼音缩写");
            //spinner.setSelectedIndex(2);
        }

        getSearchHistory();

        setPopWindow();
    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {
        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if (mCanLoadMore) {
                //这里没有下拉加载
            }
        }
    };

    private void getSearchHistory() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<String> fd = DatabaseManager.getAllInputHistory(getApplicationContext());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mSearchHistoryRecyclerViewAdapter.setData(fd);
                    }
                });
            }
        }).start();
    }

    //执行历史记录清楚
    private void showDeleteHistoryDialog() {
        if (mCHistoryDeleteDialog == null) {
            mCHistoryDeleteDialog = new CHistoryDeleteDialog(this);
            mCHistoryDeleteDialog.setItemClickListener(new CHistoryDeleteDialog.OnItemClick() {
                @Override
                public void onItemClick(int position) {
                    if (position == 1) {
                        DatabaseManager.deleteAllInputHistory(getApplicationContext());
                        getSearchHistory();
                    }
                }
            });
            mCHistoryDeleteDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                }
            });
            Window window = mCHistoryDeleteDialog.getWindow();
            window.setGravity(Gravity.BOTTOM);
            window.setWindowAnimations(R.style.dialog_bottom_anim_style);
        }
        mCHistoryDeleteDialog.show();
    }

    private android.animation.Animator mAnimatorSearch;
    private android.animation.Animator mAnimatorCondition;
    private android.animation.Animator mAnimatorContent;

    /**
     * @desc 动画隐藏标题栏，true 显示， false 隐藏
     * @author taoli
     * @time 2017/2/15 0015
     */
    private void showHideTitleBar(boolean tag) {
        if (mAnimatorSearch != null && mAnimatorSearch.isRunning()) {
            mAnimatorSearch.cancel();
        }
        if (mAnimatorCondition != null && mAnimatorCondition.isRunning()) {
            mAnimatorCondition.cancel();
        }
        if (mAnimatorContent != null && mAnimatorContent.isRunning()) {
            mAnimatorContent.cancel();
        }
        if (tag) {
            mAnimatorSearch = ObjectAnimator.ofFloat(mSearchControlCl, "translationY", mSearchControlCl.getTranslationY(), 0);
            mAnimatorSearch.setStartDelay(80);
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_cl, "translationY", condition_cl.getTranslationY(), getResources().getDimension(R.dimen.search_control_height));
            mAnimatorCondition.setStartDelay(40);
            mAnimatorContent = ObjectAnimator.ofFloat(mSearchResultcl, "translationY", mSearchResultcl.getTranslationY(), getResources().getDimension(R.dimen.search_control_height));
        } else {
            mAnimatorSearch = ObjectAnimator.ofFloat(mSearchControlCl, "translationY", mSearchControlCl.getTranslationY(), -mSearchControlCl.getHeight());
            mAnimatorCondition = ObjectAnimator.ofFloat(condition_cl, "translationY", condition_cl.getTranslationY(), 0);
            mAnimatorCondition.setStartDelay(40);
            mAnimatorContent = ObjectAnimator.ofFloat(mSearchResultcl, "translationY", mSearchResultcl.getTranslationY(), 0);
            mAnimatorContent.setStartDelay(80);
        }
        mAnimatorSearch.start();
        mAnimatorCondition.start();
        mAnimatorContent.start();
    }

    private void menuCollapse() {
        showHideTitleBar(false);
    }

    private void menuExpand() {
        showHideTitleBar(true);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mModeSelectPopWindow.isShowing()) {
            mModeSelectPopWindow.dismiss();
            return true;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (mModeSelectPopWindow != null && mModeSelectPopWindow.isShowing()) {
                mModeSelectPopWindow.dismiss();
                return true;
            }else{
                finishAfterTransition();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private int mDeletePosition = -1;
    private void showDeleteItemDialog(final int positionStock) {
        final Isszmbalv3StockInfo isszmbalv3StockInfo = mIsszmbalv3StockRecyclerViewAdapter.getItem(positionStock);
        DialogUtil.showDeleteItemDialog(this, isszmbalv3StockInfo.item_name.trim(), new Runnable() {
            @Override
            public void run() {
            }
        }, new Runnable() {
            @Override
            public void run() {
                mDeletePosition = positionStock;
                new DeleteIsszmbalv3StockInfoTask().execute(isszmbalv3StockInfo.item_no);
            }
        });
    }

    private void showTipsDialog(final String tips){
        DialogUtil.showTipsDialog(this, tips, new Runnable() {
            @Override
            public void run() {
            }
        });
    }

    private void setPopWindow() {
        View main_popup_window = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_isszmbalv3_stock_search_mode_select, null);
        mModeSelectPopWindow = new PopupWindow(main_popup_window, (int) getResources().getDimension(R.dimen.setting_popup_width), ViewGroup.LayoutParams.WRAP_CONTENT);
        mModeSelectPopWindow.setAnimationStyle(R.style.pop_window_anim_left_style);
        main_popup_window.findViewById(R.id.search_no_btn).setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                mSearchMode = SEARCH_BY_STOCKNO;
                search_mode_tv.setText("条码/序号");
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mIsszmbalv3StockRecyclerView.getWindowToken(), 0);
                mModeSelectPopWindow.dismiss();
                Intent intent = new Intent();
                intent.setClass(SearchIsszmbalv3StockActivity.this, MipcaActivityCapture.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, ACTIVITY_RESULT_BARCODE_PICK);
            }
        });
        main_popup_window.findViewById(R.id.search_name_btn).setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                mSearchMode = SEARCH_BY_STOCKNAME;
                search_mode_tv.setText("中文名称");
                getIsszmbalv3StockResultInfoList(true);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mIsszmbalv3StockRecyclerView.getWindowToken(), 0);
                mModeSelectPopWindow.dismiss();
            }
        });
        main_popup_window.findViewById(R.id.search_spell_btn).setOnClickListener(new View.OnClickListener() {
            public final void onClick(View v) {
                mSearchMode = SEARCH_BY_STOCKSPELL;
                search_mode_tv.setText("拼音缩写");
                getIsszmbalv3StockResultInfoList(true);
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mIsszmbalv3StockRecyclerView.getWindowToken(), 0);
                mModeSelectPopWindow.dismiss();
            }
        });

        mModeSelectPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mModeSelectPopWindow.setOutsideTouchable(true);
        mModeSelectPopWindow.setTouchable(true);
        mModeSelectPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                search_mode_iv.animate().rotation(0);
            }
        });
        if (main_popup_window != null) {
            main_popup_window.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
        }
    }

    private void getIsszmbalv3StockResultInfoList(boolean headerOrFooter) {
        if (this.isFinishing()) {
            return;
        }
        if ( TextUtils.isEmpty(mSearchStr)) {
            mHistoryRl.setVisibility(View.GONE);
            spin_kit.setVisibility(View.GONE);
            mGetStockFailTipLy.setVisibility(View.VISIBLE);
            mPtrFrame.setVisibility(View.GONE);
            mPtrFrame.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPtrFrame.refreshComplete();
                }
            }, 0);
            return;
        }
        try {
            semp.acquire();
        } catch (InterruptedException e) {
        }
        new GetIsszmbalv3StockResultInfoListTask(headerOrFooter).execute();
    }

    private class GetIsszmbalv3StockResultInfoListTask extends AsyncTask<Void, Void, List<Isszmbalv3StockInfo>> {
        private boolean mHeaderOrFooter;

        public GetIsszmbalv3StockResultInfoListTask(boolean headerOrFooter) {
            mHeaderOrFooter = headerOrFooter;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mHistoryRl.setVisibility(View.GONE);
            spin_kit.setVisibility(View.VISIBLE);
            mPtrFrame.setVisibility(View.VISIBLE);
            mGetStockFailTipLy.setVisibility(View.GONE);
        }

        @Override
        protected List<Isszmbalv3StockInfo> doInBackground(Void... params) {
            if (SearchIsszmbalv3StockActivity.this.isFinishing()) {
                return null;
            }
            int r = 0;
            if (mHeaderOrFooter == true) {
                mReadIndex = 0;
            }
            r = mReadIndex;
            List<Isszmbalv3StockInfo> result = null;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                result = DatabaseManager.getIsszmbalv3StockInfoListFromSqlServer(SearchIsszmbalv3StockActivity.this, r, -1, -1, mSearchMode, SortMode, mSearchStr);
            }else{
                result = DatabaseManager.getIsszmbalv3StockInfoListFromLocal(SearchIsszmbalv3StockActivity.this, r, -1, mSearchMode, SortMode, mSearchStr);
            }
            mReadIndex = mReadIndex + result.size();
            return result;
        }

        @Override
        protected void onPostExecute(final List<Isszmbalv3StockInfo> result) {
            super.onPostExecute(result);
            if (SearchIsszmbalv3StockActivity.this.isFinishing()) {
                return;
            }

            if (result != null) {
                synchronized (mLock) {
                    Drawable mPointMenuBmp = initCounterResources(mReadIndex);
                    mPointMenuBmp.setBounds(0, 0, mPointMenuBmp.getMinimumWidth(), mPointMenuBmp.getMinimumHeight());
                    mSearchEt.setCompoundDrawables(mPointMenuBmp, null, null, null);

                    if (result != null && result.size() != 0) {
                    } else {
                    }

                    if (mHeaderOrFooter == true) {
                        Message _Msg = mHandler.obtainMessage(REFRESH_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    } else {
                        Message _Msg = mHandler.obtainMessage(LOAD_DATA_FINISH, result);
                        mHandler.sendMessage(_Msg);
                    }
                }
            }
            mPtrFrame.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mPtrFrame.refreshComplete();
                }
            }, 0);
        }
    }

    private class DeleteIsszmbalv3StockInfoTask extends AsyncTask<String, Void, String> {
        public DeleteIsszmbalv3StockInfoTask() {
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            String stockNo = params[0];
            long row = -1;
            if (BarApplication.getInstance().mDatabaseIsSqlServer) {
                row = DatabaseManager.deleteIsszmbalv3StockInfoFromSqlServer(SearchIsszmbalv3StockActivity.this, stockNo);
            }else{
                row = DatabaseManager.deleteIsszmbalv3StockInfoFromLocal(SearchIsszmbalv3StockActivity.this, stockNo);
            }
            return String.valueOf(row);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.equals("1")) {
                mIsszmbalv3StockRecyclerViewAdapter.removeData(mDeletePosition);
                mIsszmbalv3StockRecyclerViewAdapter.notifyItemRemoved(mDeletePosition);
            }else{
                showTipsDialog("删除失败，请保存截断中文名后再试");
            }
        }
    }

    private void showResultView() {
        if (mIsszmbalv3StockRecyclerViewAdapter.getItemCount() == 0) {
            mIsszmbalv3StockRecyclerView.setVisibility(View.GONE);
            spin_kit.setVisibility(View.GONE);
            mGetStockFailTipLy.setVisibility(View.VISIBLE);
        } else {
            mIsszmbalv3StockRecyclerView.setVisibility(View.VISIBLE);
            spin_kit.setVisibility(View.GONE);
            mGetStockFailTipLy.setVisibility(View.GONE);
        }
        mHistoryRl.setVisibility(View.GONE);
    }

    private Drawable initCounterResources(int number) {
        int iconHeight = (int) Utils.sp2px(getResources(), 20f);
        int iconWidth = iconHeight;
        if(number < 10 )
            iconWidth = (int) Utils.sp2px(getResources(), 20f);
        else if( number < 100 )
            iconWidth = (int) Utils.sp2px(getResources(), 25f);
        else if( number < 1000 )
            iconWidth = (int) Utils.sp2px(getResources(), 30f);
        else if( number < 10000 )
            iconWidth = (int) Utils.sp2px(getResources(), 35f);
        int pading = (int) Utils.sp2px(getResources(), 2f);
        Bitmap bitmap = Bitmap.createBitmap(iconWidth, iconHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        RectF rect = new RectF(0, 0, canvas.getWidth(), canvas.getHeight());
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
        // draw background  
        paint.setColor(Color.WHITE);
        canvas.drawOval(rect, paint);
        paint.setColor(Color.RED);
        canvas.drawOval(new RectF(pading, pading, rect.width()-pading, rect.height()-pading), paint);
        // draw text  
        paint.setColor(Color.WHITE);
        paint.setStrokeWidth(3);
        paint.setTextSize(iconHeight * 0.5f);
        paint.setTextAlign(Paint.Align.CENTER);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
        float baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
        canvas.drawText(String.valueOf(number), rect.centerX(), baseline, paint);
        return new BitmapDrawable(getResources(), bitmap);
    }

    private void displayWithAnimator(final View v, final float alpha, final int time) {
        int sysVersion = Integer.parseInt(Build.VERSION.SDK);
        if (sysVersion >= 11) {
            final ValueAnimator animator = ValueAnimator.ofFloat(ViewHelper.getAlpha(v), alpha);
            animator.setDuration(time);
            animator.setInterpolator(new DecelerateInterpolator());//线性效果变化
            animator.start();
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator valueAnimator) {
                    Float integer = (Float) valueAnimator.getAnimatedValue();
                    ViewHelper.setAlpha(v, integer);
                }
            });
        } else {
            AlphaAnimation alphaAnimation = new AlphaAnimation(ViewHelper.getAlpha(v), alpha);
            alphaAnimation.setDuration(time);
            v.startAnimation(alphaAnimation);
            alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    ViewHelper.setAlpha(v, alpha);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_RESULT_BARCODE_PICK) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    //mImageView.setImageBitmap((Bitmap) data.getParcelableExtra("bitmap"));
                    mSearchEt.setText(bundle.getString("result"));
                    mSearchStr = bundle.getString("result");
                    getIsszmbalv3StockResultInfoList(true);
                }
            }
        }
        if (requestCode == ACTIVITY_RESULT_SPEECH) {
            if (data != null && data.hasExtra("result")) {
                String searchStr = data.getStringExtra("result");
                mIsszmbalv3StockRecyclerView.requestFocus();
                mSearchStr = searchStr;
                mSearchEt.setText(mSearchStr);
                getIsszmbalv3StockResultInfoList(true);
            }
        }
        if (requestCode == ACTIVITY_RESULT_STOCK_DETAIL) {
            if (resultCode == RESULT_OK) {
                getIsszmbalv3StockResultInfoList(true);
            }
        }
    }
}
